﻿using System;
using System.Web.Mvc;
using Learun.Application.Base.SystemModule;
using Learun.Application.Organization;
using Learun.Util;
using Learun.Util.Operat;

namespace Learun.Application.Web.Controllers
{
    /// <summary>
    /// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
    /// Copyright (c) 2013-2018 Hexagon PPM
    /// 创建人：研发部
    /// 日 期：2017.03.08
    /// 描 述：登录控制器
    /// </summary>
    [HandlerLogin(FilterMode.Ignore)]
    public class LoginController : MvcControllerBase
    {
        #region 模块对象
        private UserIBLL userBll = new UserBLL();
        #endregion

        #region 视图功能
        /// <summary>
        /// 登录页面
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            OperatorHelper.Instance.EmptyCurrent();//add by chenkai 20210323 解决登陆后非退出跳转到登录页登录异常问题
            OperatorHelper.Instance.ClearCurrentErrorNum();
            return View();
        }


        /// <summary>
        /// 下载APP
        /// </summary>
        /// <returns></returns>
        public ActionResult AppDownload()
        {
            return View();
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 生成验证码
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult VerifyCode()
        {
            return File(new VerifyCode().GetVerifyCode(), @"image/Gif");
        }

        /// <summary>
        /// 获取用户登录信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AjaxOnly]
        [HandlerLogin(FilterMode.Enforce)]
        public ActionResult GetUserInfo()
        {
            var data = LoginUserInfo.Get();
            data.imUrl = Config.GetValue("IMUrl");
            data.imOpen = Config.GetValue("IMOpen");
            data.password = null;
            data.secretkey = null;
            return Success(data);
        }
        #endregion

        #region 提交数据
        /// <summary>
        /// 安全退出
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        [HandlerLogin(FilterMode.Enforce)]
        public ActionResult OutLogin()
        {
            var userInfo = LoginUserInfo.Get();
            LogEntity logEntity = new LogEntity();
            logEntity.F_CategoryId = 1;
            logEntity.F_OperateTypeId = ((int)OperationType.Exit).ToString();
            logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Exit);
            logEntity.F_OperateAccount = userInfo.account + "(" + userInfo.realName + ")";
            logEntity.F_OperateUserId = userInfo.userId;
            logEntity.F_ExecuteResult = 1;
            logEntity.F_ExecuteResultJson = "退出系统";
            logEntity.F_Module = Config.GetValue("SoftName");
            logEntity.WriteLog();
            Session.Abandon();                                          //清除当前会话
            Session.Clear();                                            //清除当前浏览器所有Session
            OperatorHelper.Instance.EmptyCurrent();
            return Success("退出系统");
        }
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="username">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="verifycode">验证码</param>
        /// <returns></returns>
        [HttpPost]
        [AjaxOnly]
        public ActionResult CheckLogin(string username, string password, string verifycode)
        {
            int error = OperatorHelper.Instance.GetCurrentErrorNum();
            if (error >= 3)
            {
                //服务端校验是否输入验证码
                if (string.IsNullOrEmpty(verifycode))
                {
                    return Fail("请输入验证码");
                }

                #region 验证码验证
                verifycode = Md5Helper.Encrypt(verifycode.ToLower(), 16);
                if (Session["session_verifycode"].IsEmpty() || verifycode != Session["session_verifycode"].ToString())
                {
                    return Fail("验证码错误");
                }
                #endregion
            }

            #region add by chenkai 20210322
            //int iErrCount = Convert.ToInt32(Config.GetValue("LoginErrCount", "5"));
            //DateTime? errorTime = OperatorHelper.Instance.GetErrorTime();
            //if (errorTime != null)
            //{
            //    int iLockMinute = Convert.ToInt32(Config.GetValue("LoginLockMinute", "10"));
            //    if (Convert.ToDateTime(errorTime).AddMinutes(iLockMinute) > DateTime.Now)
            //    {
            //        return Fail(string.Format("连续登录失败{0}次，锁定该账户{1}分钟！", iErrCount, iLockMinute), error);
            //    }
            //}
            #endregion

            #region 内部账户验证
            UserEntity userEntity = userBll.CheckLogin(username, password);

            #region 写入日志
            LogEntity logEntity = new LogEntity();
            logEntity.F_CategoryId = 1;
            logEntity.F_OperateTypeId = ((int)OperationType.Login).ToString();
            logEntity.F_OperateType = EnumAttribute.GetDescription(OperationType.Login);
            logEntity.F_OperateAccount = username + "(" + userEntity.F_RealName + ")";
            logEntity.F_OperateUserId = !string.IsNullOrEmpty(userEntity.F_UserId) ? userEntity.F_UserId : username;
            logEntity.F_Module = Config.GetValue("SoftName");
            #endregion

            if (!userEntity.LoginOk)//登录失败
            {
                //写入日志
                logEntity.F_ExecuteResult = 0;
                logEntity.F_ExecuteResultJson = "登录失败:用户名或密码错误！";
                logEntity.WriteLog();
                int num = OperatorHelper.Instance.AddCurrentErrorNum();
                #region add by chenkai 20210322
                //if (num % iErrCount == 0)
                //{
                //    OperatorHelper.Instance.SaveErrorTime();
                //}
                #endregion
                return Fail(userEntity.LoginMsg, num);
                //return Fail("用户名或密码错误！", num);
            }
            else
            {
                WebHelper.WriteCookie("LoginUrl", WebHelper.HtmlEncode(Request.UrlReferrer.AbsolutePath), true);//保存登录网址
                OperatorHelper.Instance.AddLoginUser(userEntity.F_Account, "Learun_ADMS_6.1_PC", null);//写入缓存信息
                //写入日志
                logEntity.F_ExecuteResult = 1;
                logEntity.F_ExecuteResultJson = "登录成功";
                logEntity.WriteLog();
                OperatorHelper.Instance.ClearCurrentErrorNum();
                //OperatorHelper.Instance.ClearErrorTime();

                #region add by chenkai 20210322
                bool isUpdatePassWord = true;
                //判断定期修改密码周期
                if (userEntity.PasswordUpdateTime == null)
                {
                    isUpdatePassWord = false;
                }
                else
                {
                    //DateTime start = Convert.ToDateTime(userEntity.PasswordUpdateTime);
                    //DateTime end = DateTime.Now;
                    //if (end > start)
                    //{
                    //    TimeSpan sp = end.Subtract(start);
                    //    int iCycle = Convert.ToInt32(Config.GetValue("PasswordUpdateCycle", "90"));
                    //    int iDays = sp.Days;
                    //    if (iDays > iCycle)
                    //    {
                    //        isUpdatePassWord = false;
                    //    }
                    //}
                }

                var jsonData = new
                {
                    UpdatePassWord = isUpdatePassWord
                };
                #endregion
                return Success("登录成功", jsonData);
            }
            #endregion
        }
        #endregion
    }
}